package com.assa.subscriber.creacionorden;

import java.io.StringWriter;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.assa.subscriber.EventSubscriber;
import com.assa.ws.client.notify.NotifyClient;
import com.grupoassa.utils.IdGenerator;
import com.grupoassa.utils.XmlUtils;

public class CreacionOrdenEventSubscriber implements EventSubscriber {

	private Template template;
	private static Log logger = LogFactory.getLog(CreacionOrdenEventSubscriber.class);
	private NotifyClient notifyService;

	public CreacionOrdenEventSubscriber() throws Exception {
		Velocity.init();
		this.template = Velocity.getTemplate("./creacionOrdenEvent.vm");
	}
	
	public void setNotifyService(NotifyClient notifyService) {
		this.notifyService = notifyService;
	}

	public void notifyEvent(Map<String, String> parameters) {
		try {
			String xmlRequest = buildVelocityTemplate(parameters);
			this.notifyService.notifyEvent(xmlRequest);
		} catch (Exception e) {
			this.logger.error(e);
		}
	}

	private String buildVelocityTemplate(Map<String, String> params) throws Exception {
		VelocityContext context = new VelocityContext(params);
		context.put("instanceID", IdGenerator.getGlobalInstanceId());
		StringWriter output = new StringWriter();
		template.merge(context, output);
		return XmlUtils.removeSpecialCharacters(output.toString());
	}	
	
	
}
